<template>
  <div ref="chartRef" :style="{ width: '100%', height: chartHeight }"></div>
</template>

<script setup lang="ts">
// 引入 echarts 核心模块，核心模块提供了 echarts 使用必须要的接口。
import * as echarts from "echarts/core";
// 引入折线图图表，图表后缀都为 Chart
import { LineChart } from "echarts/charts";
// 引入标题，提示框，直角坐标系，数据集，内置数据转换器组件，组件后缀都为 Component
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
} from "echarts/components";
// 标签自动布局、全局过渡动画等特性
import { LabelLayout, UniversalTransition } from "echarts/features";
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from "echarts/renderers";
import { onMounted, onUnmounted, ref, watch, defineProps, withDefaults } from "vue";

// 定义组件接收的属性
interface Props {
  chartHeight?: string;
  data?: any;
  title?: string;
  showTitle?: boolean;
  themeColor?: string;
}

const props = withDefaults(defineProps<Props>(), {
  chartHeight: '300px',
  title: '数据统计',
  showTitle: false,
  themeColor: '#2B5AED'
});

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LineChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer,
]);

const chartRef = ref<HTMLElement | null>(null);
let myChart: echarts.ECharts | null = null;

// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    myChart = echarts.init(chartRef.value);
    updateChart();
  }
};

// 更新图表数据
const updateChart = () => {
  if (!myChart) return;
  
  // 默认数据
  const defaultData = {
    xAxis: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
    series: [820, 932, 901, 934, 1290, 1330, 1320]
  };
  
  let xAxisData: string[] = [];
  let seriesData: number[] = [];
  
  // 处理不同格式的数据
  if (props.data) {
    // 如果数据是数组且包含date和count属性（匹配mock数据格式）
    if (Array.isArray(props.data) && props.data.length > 0 && 'date' in props.data[0] && 'count' in props.data[0]) {
      xAxisData = props.data.map((item: any) => item.date);
      seriesData = props.data.map((item: any) => item.count);
    } 
    // 如果数据已经是预期的xAxis和series格式
    else if (props.data.xAxis && props.data.series) {
      xAxisData = props.data.xAxis;
      seriesData = props.data.series;
    }
    // 如果数据是简单数组
    else if (Array.isArray(props.data)) {
      if (typeof props.data[0] === 'object') {
        // 尝试提取第一个和第二个属性作为x轴和值
        const keys = Object.keys(props.data[0]);
        if (keys.length >= 2) {
          xAxisData = props.data.map((item: any) => item[keys[0]]);
          seriesData = props.data.map((item: any) => item[keys[1]]);
        } else {
          // 回退到默认
          xAxisData = defaultData.xAxis;
          seriesData = defaultData.series;
        }
      } else {
        // 如果是简单值数组，使用索引作为x轴
        xAxisData = props.data.map((_: any, index: number) => `Day ${index + 1}`);
        seriesData = props.data;
      }
    } else {
      console.warn('无法识别的数据格式，使用默认数据');
      xAxisData = defaultData.xAxis;
      seriesData = defaultData.series;
    }
  } else {
    // 没有提供数据，使用默认数据
    xAxisData = defaultData.xAxis;
    seriesData = defaultData.series;
  }
  
  myChart.setOption({
    title: {
      text: props.title,
      left: 'center',
      show: props.showTitle
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.8)',
      borderColor: '#F2F3F5',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: props.themeColor,
          opacity: 0.5
        }
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: props.showTitle ? '15%' : '5%',
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: xAxisData,
      boundaryGap: false,
      axisLine: {
        lineStyle: {
          color: '#E5E6EB'
        }
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#86909C'
      }
    },
    yAxis: {
      type: "value",
      splitLine: {
        lineStyle: {
          color: '#E5E6EB',
          type: 'dashed'
        }
      },
      axisLabel: {
        color: '#86909C'
      }
    },
    series: [
      {
        name: props.title,
        data: seriesData,
        type: "line",
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        showSymbol: false,
        emphasis: {
          scale: true,
          focus: 'series',
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.2)'
          }
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: echarts.color.modifyAlpha(props.themeColor, 0.5) },
            { offset: 1, color: echarts.color.modifyAlpha(props.themeColor, 0.05) }
          ])
        },
        itemStyle: {
          color: props.themeColor
        },
        lineStyle: {
          width: 3,
          shadowColor: 'rgba(0, 0, 0, 0.2)',
          shadowBlur: 10,
          shadowOffsetY: 5
        }
      }
    ],
    animation: true
  });
};

// 处理窗口大小变化
const handleResize = () => {
  myChart?.resize();
};

// 监听数据变化
watch(() => props.data, () => {
  updateChart();
}, { deep: true });

// 监听主题色变化
watch(() => props.themeColor, () => {
  updateChart();
});

onMounted(() => {
  initChart();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  myChart?.dispose();
});
</script>

<style scoped lang="less">
.chart-container {
  position: relative;
  overflow: hidden;
  border-radius: 4px;
  transition: all 0.3s;
}
</style>